package com.example.g3a1.notice

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.base.cons.ApiServer
import com.example.base.cons.entity.NoticeBeanItem

@Suppress("UNUSED_EXPRESSION")
class NoticeDataSource(apiServer: ApiServer): PagingSource<Int, NoticeBeanItem>() {
    lateinit var apiServer: ApiServer
    init{
        this.apiServer = apiServer
    }
    override fun getRefreshKey(state: PagingState<Int, NoticeBeanItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, NoticeBeanItem> {
        try {
            val current = params.key ?: 0
            val notices = apiServer.getNotices(current, 10)
            val nextPage = if (notices.data.size == 10) current + 1 else null
            return LoadResult.Page(notices.data, null, nextPage)
        }catch (e:Exception){
            return LoadResult.Error(e)
        }
    }
}